package com.ledou44.apollolearn.util;

import com.ctrip.framework.apollo.ConfigService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.java.Log;

import java.util.Date;

@Log
public class JwtUtil {

    /**
     * token 过期时间，从apollo配置中心获取
     */
    private static final long EXPIRE_TIME = 30 * 60 * 1000;

    /**
     * token 私钥，从apollo配置中心获取
     */
    private static final String TOKEN_SECRET = ConfigService.getAppConfig().getProperty("TOKEN_SECRET","TOKEN_SECRET");


    /**
     * 生成签名，30分钟过期
     */
    public static String sign() {
        return Jwts.builder().setSubject("worker")
                .claim("userId", "10002")
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET).compact();
    }

    /**
     * 检验token是否正确
     */
    public static String getUserId(String token){
        String result = "";
        try {
            Claims claims = Jwts.parser().setSigningKey(TOKEN_SECRET).parseClaimsJws(token).getBody();
            result = claims.get("userId", String.class);
        } catch (Exception e) {
            log.warning("token解析失败");
        }
        return result;
    }
}
